//
//  WBStatusViewListModel.swift
//  新浪微博
//
//  Created by shanlin on 2017/8/29.
//  Copyright © 2017年 shanlin. All rights reserved.
//

import Foundation

///上拉刷新最大尝试次数
private let maxPullupTryTime = 3


class WBStatusViewListModel { 
    
    //微博模型数组懒加载
    lazy var StatusList = [WBStatus]()
    //上拉刷新错误次数
    private var pullupErrorTimes = 0
    
    
    //加载微博列表
    ///
    /// - parameter pullup :     是否上拉刷新标记
    /// - parameter completion :  完成回调[网络请求是否成功, 是否刷新表格]
    func loadStatus(pullup: Bool, completion:@escaping (_ isSuccess:Bool, _ shouldRefresh:Bool)->()) {
        
        if pullup && pullupErrorTimes > maxPullupTryTime {
            completion(true, false)
            return
        }
        
        
        
        
        //since_id 取出数组中第一条微博的id
        let since_id = pullup ? 0 :(StatusList.first?.id ?? 0)
        let max_id = !pullup ? 0 :(StatusList.last?.id ?? 0)
        
        
        
        
        WBNetworkManager.shared.statusList(since_id: since_id,max_id: max_id) { (list, isSuccess) in
            //1.字典转模型
            
            guard let array = NSArray.yy_modelArray(with: WBStatus.self, json: list ?? []) as? [WBStatus] else {
                completion(isSuccess,false)
                return
            }
            print("刷新到\(array.count)条数据")
            //2.拼接数据 应该把结果数组拼接在数组前面
            if pullup {
                //上拉刷新结束后,将结果拼接在数组的末尾
                self.StatusList += array
            } else {
                self.StatusList = array + self.StatusList
            }
            
            // 3. 判断上拉刷新的数据量
            if pullup && array.count == 0 {
                self.pullupErrorTimes += 1
                completion(isSuccess, false)
            }else {
                //3.完成回调
                completion(isSuccess,true)
            }
            
                
            
            
        }
    }
   
    
    
}
